#include "queryhistorydialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTreeWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QDialogButtonBox>
#include <QHeaderView>
#include <QTreeWidgetItem>
#include <QDateTime>
#include <QMessageBox>
#include <QApplication>
#include <QClipboard>

QueryHistoryDialog::QueryHistoryDialog(QueryHistoryManager *manager, QWidget *parent)
    : QDialog(parent)
    , m_historyManager(manager)
{
    setupUI();
    loadHistory();
    
    // 连接信号和槽
    connect(m_historyManager, &QueryHistoryManager::historyUpdated, this, &QueryHistoryDialog::loadHistory);
}

void QueryHistoryDialog::loadHistory()
{
    QList<QueryHistoryItem> items = m_historyManager->getRecentQueries(100);
    updateHistoryList(items);
}

void QueryHistoryDialog::searchHistory()
{
    QString searchTerm = m_searchEdit->text();
    QList<QueryHistoryItem> items;
    
    if (searchTerm.isEmpty()) {
        items = m_historyManager->getRecentQueries(100);
    } else {
        items = m_historyManager->searchQueries(searchTerm);
    }
    
    updateHistoryList(items);
}

void QueryHistoryDialog::onItemDoubleClicked()
{
    useSelectedQuery();
}

void QueryHistoryDialog::onItemSelected()
{
    QList<QTreeWidgetItem *> selectedItems = m_historyTree->selectedItems();
    m_useButton->setEnabled(!selectedItems.isEmpty());
    
    if (!selectedItems.isEmpty()) {
        QTreeWidgetItem *item = selectedItems.first();
        m_selectedQuery = item->data(0, Qt::UserRole).toString();
    }
}

void QueryHistoryDialog::clearHistory()
{
    int result = QMessageBox::question(this, tr("Clear History"), 
                                      tr("Are you sure you want to clear the query history?"));
    
    if (result == QMessageBox::Yes) {
        m_historyManager->clearHistory();
    }
}

void QueryHistoryDialog::useSelectedQuery()
{
    if (!m_selectedQuery.isEmpty()) {
        emit querySelected(m_selectedQuery);
        accept();
    }
}

void QueryHistoryDialog::setupUI()
{
    setWindowTitle(tr("Query History"));
    setModal(true);
    resize(800, 500);
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 搜索框
    QHBoxLayout *searchLayout = new QHBoxLayout;
    m_searchEdit = new QLineEdit;
    m_searchEdit->setPlaceholderText(tr("Search queries..."));
    connect(m_searchEdit, &QLineEdit::textChanged, this, &QueryHistoryDialog::searchHistory);
    
    QPushButton *searchButton = new QPushButton(tr("Search"));
    connect(searchButton, &QPushButton::clicked, this, &QueryHistoryDialog::searchHistory);
    
    searchLayout->addWidget(m_searchEdit);
    searchLayout->addWidget(searchButton);
    mainLayout->addLayout(searchLayout);
    
    // 历史记录树
    m_historyTree = new QTreeWidget;
    m_historyTree->setHeaderLabels({tr("Query"), tr("Database"), tr("Time")});
    m_historyTree->setColumnWidth(0, 400);
    m_historyTree->setColumnWidth(1, 150);
    m_historyTree->setColumnWidth(2, 150);
    m_historyTree->setRootIsDecorated(false);
    m_historyTree->setAlternatingRowColors(true);
    m_historyTree->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_historyTree->setSelectionMode(QAbstractItemView::SingleSelection);
    
    connect(m_historyTree, &QTreeWidget::itemDoubleClicked, this, &QueryHistoryDialog::onItemDoubleClicked);
    connect(m_historyTree, &QTreeWidget::itemSelectionChanged, this, &QueryHistoryDialog::onItemSelected);
    
    mainLayout->addWidget(m_historyTree);
    
    // 按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    
    m_clearButton = new QPushButton(tr("Clear History"));
    connect(m_clearButton, &QPushButton::clicked, this, &QueryHistoryDialog::clearHistory);
    buttonLayout->addWidget(m_clearButton);
    
    buttonLayout->addStretch();
    
    m_useButton = new QPushButton(tr("Use Query"));
    m_useButton->setEnabled(false);
    connect(m_useButton, &QPushButton::clicked, this, &QueryHistoryDialog::useSelectedQuery);
    buttonLayout->addWidget(m_useButton);
    
    QPushButton *copyButton = new QPushButton(tr("Copy Query"));
    connect(copyButton, &QPushButton::clicked, this, [this]() {
        if (!m_selectedQuery.isEmpty()) {
            QApplication::clipboard()->setText(m_selectedQuery);
            QMessageBox::information(this, tr("Copied"), tr("Query copied to clipboard"));
        }
    });
    buttonLayout->addWidget(copyButton);
    
    m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
    connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
    buttonLayout->addWidget(m_buttonBox);
    
    mainLayout->addLayout(buttonLayout);
}

void QueryHistoryDialog::updateHistoryList(const QList<QueryHistoryItem> &items)
{
    m_historyTree->clear();
    
    for (const QueryHistoryItem &item : items) {
        QTreeWidgetItem *treeItem = new QTreeWidgetItem(m_historyTree);
        treeItem->setText(0, item.query);
        treeItem->setText(1, item.databaseName);
        treeItem->setText(2, item.timestamp.toString("yyyy-MM-dd hh:mm:ss"));
        treeItem->setData(0, Qt::UserRole, item.query);
        
        // 限制显示的查询长度
        QString displayQuery = item.query;
        if (displayQuery.length() > 100) {
            displayQuery = displayQuery.left(100) + "...";
        }
        treeItem->setText(0, displayQuery);
    }
    
    m_historyTree->header()->resizeSections(QHeaderView::ResizeToContents);
}